package com.jushu.storbox;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.SimpleDateFormat;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;

import com.jushu.storbox.actions.Actions;
import com.jushu.storbox.callback.ICallback;
import com.jushu.storbox.callback.IDownloadCallback;
import com.jushu.storbox.callback.IDownloadThumbnailCallback;
import com.jushu.storbox.constant.ClientConfig;
import com.jushu.storbox.constant.Constant;
import com.jushu.storbox.constant.UiConstant;
import com.jushu.storbox.database.DAOFactory;
import com.jushu.storbox.database.IFileDao;
import com.jushu.storbox.entities.FileFolderInfo;
import com.jushu.storbox.filesystem.FileManagerFactory;
import com.jushu.storbox.filesystem.iFileManager;
import com.jushu.storbox.service.CloudDriveService;
import com.jushu.storbox.service.ICloudDriveService;
import com.jushu.storbox.task.tqueue.DownloadTask;
import com.jushu.storbox.task.tqueue.ShareDownloadTask;
import com.jushu.storbox.util.DirectoryUtil;
import com.jushu.storbox.util.LogUtil;
import com.jushu.storbox.util.PublicTools;
import com.jushu.storbox.util.identity.FileMD5Identity;
import com.huawei.sharedrive.sdk.android.service.CommonClient;

public class FileDownloadActivity extends Activity
{
    private FileFolderInfo mFileFolderInfo;
    
    private TextView mTvTitle;
    
    private ImageView mIvLabel;
    
    private TextView mTvName;
    
    private TextView mTvSize;
    
    private ProgressBar mProgressbar;
    
    private ICloudDriveService mCloudDriveService;
    
    private IDownloadThumbnailCallback mDownloadThumbnailCallback;
    
    private Handler mHandler;
    
    private ServiceConnection mServiceConnection;
    
    private String mThumbnailIconPath;
    
    private String lastPath;
    
    private ICallback mDownloadCallback;
    
    private String mFilePath;
    
    public static final String TAG = "FileDownloadActivity";
    
    private DownloadTask mTask;
    
    private ShareDownloadTask mShareTask;
    
    private boolean isFirstMusic;
    
    private SeekBar seekBar;
    
    private ImageView btnPlayOrPause;
    
    private TextView currentTime_tv;
    
    private TextView maxTime_tv;
    
    private LinearLayout music_ll;
    
    private int maxTime = 0;
    
    private int currentTime;
    
    private Thread musicThread;
    
    private boolean isLoop;
    
    private boolean isPlaying;
    
    private Handler musicHandler;
    
    private boolean isDownloadMusic;
    
    private String musicPath;
    
    private static final int HAS_PIC_THUMBNAIL = 0x90;
    
    private static final int FILE_START_DOENALOAD = 0x91;
    
    private static final int FILE_PROGRESS_DOWNLOAD = 0x92;
    
    private static final int FILE_DOWNLOAD_SUCCESS = 0x93;
    
    private static final int FILE_DOWNLOAD_FAIL = 0x94;
    
    private View mContentView;
    
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        Log.i("FileDownloadActivity", "oncreate");
        isDownloadMusic = getIntent().getExtras().getBoolean("isMusic", false);
        if (isDownloadMusic)
        {
            initDataFromIntentExtra();
            initPath();
            setContentView(R.layout.activity_file_download);
            initView();
            initData();
            initCloudDriveService();
            
        }
        else
        {
            initDataFromIntentExtra();
            initPath();
            setContentView(R.layout.activity_file_download);
            initView();
            initCallBack();
            initHander();
            initData();
            initCloudDriveService();
        }
        
    }
    
    private void initPath()
    {
        if (mFileFolderInfo == null)
        {
            return;
        }
        
        if (mFileFolderInfo.getIsInode() == -1)
        {
            mFilePath = DirectoryUtil.generateFileDownloadPath(this, 
            		mFileFolderInfo.getOwnerId(), mFileFolderInfo.getId(), mFileFolderInfo.getName());
            
            lastPath = DirectoryUtil.generateDownloadDir(this);
        }
        else
        {
        	mFilePath = DirectoryUtil.generateShareDownloadPath(this, 
        			mFileFolderInfo.getOwnerBy(),
        			mFileFolderInfo.getId(), 
        			mFileFolderInfo.getName());
            lastPath = DirectoryUtil.generateShareDir(this);
        }
    }
    
    private void initHander()
    {
        mHandler = new Handler()
        {
            
            @Override
            public void handleMessage(Message msg)
            {
                super.handleMessage(msg);
                switch (msg.what)
                {
                    case HAS_PIC_THUMBNAIL:
                        String thumbNailPath = (String) msg.obj;
                        
                        Bitmap bm = null;
                        FileInputStream fis = null;
                        try
                        {
                            fis = new FileInputStream(thumbNailPath);
                            bm = BitmapFactory.decodeStream(fis);
                        }
                        catch (FileNotFoundException e)
                        {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                        finally
                        {
                            if (null != fis)
                            {
                                try
                                {
                                    fis.close();
                                }
                                catch (IOException e)
                                {
                                    // TODO Auto-generated catch block
                                    e.printStackTrace();
                                }
                            }
                        }
                        if (bm != null)
                        {
                            mIvLabel.setImageBitmap(bm);
                        }
                        else
                        {
                            mIvLabel.setImageResource(R.mipmap.empty_pic);
                        }
                        
                        break;
                    case FILE_START_DOENALOAD:
                        mProgressbar.setProgress(0);
                        break;
                    case FILE_PROGRESS_DOWNLOAD:
                        int progress = (Integer) msg.obj;
                        if (progress < 0)
                        {
                            progress = 0;
                        }
                        mProgressbar.setProgress(progress);
                        break;
                    case FILE_DOWNLOAD_SUCCESS:
                        mProgressbar.setProgress(100);
//                        Toast.makeText(getApplicationContext(),
//                            getString(R.string.fileListadapter_keep_success),
//                            Toast.LENGTH_SHORT).show();
                        
                        iFileManager mdmTools = FileManagerFactory.getFileManager(FileDownloadActivity.this);
                        if (mdmTools.fileIsExist(mFilePath))
                        {
                            if (PublicTools.isFileType(mFileFolderInfo.getName(), Constant.MUSIC_TYPE))
                            {
                                isFirstMusic = true;
                                initMusic();
                            }
                            else
                            {
                                mdmTools.openFile(mFilePath, mFileFolderInfo.getSize());
                                finish();
                            }
                        }
                        
                        break;
                    case FILE_DOWNLOAD_FAIL:
                        if (msg.arg1 == 901)
                        {
                            Toast.makeText(getApplicationContext(),
                                getString(R.string.loginwait_activity_server_busy),
                                Toast.LENGTH_SHORT).show();
                        }
                        else if (msg.arg1 == Constant.DOWNLOAD_CANCEL_SUCCESS_CODE)
                        {
//                            Toast.makeText(getApplicationContext(),
//                                getString(R.string.fileListadapter_cancel_keep),
//                                Toast.LENGTH_SHORT).show();
                        }
                        else if(msg.arg1 == Constant.DOWNLOAD_FAIL_FILE_LARGERTHAN_CACHESIZE)
                        {
                            Toast.makeText(getApplicationContext(),
                                getString(R.string.download_file_larger_than_local_cache),
                                Toast.LENGTH_SHORT).show();
                        }
                        else if(msg.arg1 == UiConstant.TASK_TRANSLATE_CANCELED){
                        	//Normal cancel
                        }
                        else
                        {
                            // download fail
                            Toast.makeText(getApplicationContext(),
                                getString(R.string.download_file_cache_fail) + "(" + msg.arg1 + ")",
                                Toast.LENGTH_SHORT).show();
                        }
                        finish();
                        break;
                    case 10:
                        //  download fail
                        Toast.makeText(getApplicationContext(),
                            getString(R.string.download_file_cache_fail),
                            Toast.LENGTH_SHORT).show();
                        
                        Intent intent = new Intent(Constant.REFRESH_APPSTORE_ACTION);
                        intent.putExtra("fId", msg.obj.toString());
                        sendBroadcast(intent);
                        finish();
                        break;
                    case 11:
                        // download fail
                        Toast.makeText(getApplicationContext(),
                            getString(R.string.fileListadapter_file_notfond),
                            Toast.LENGTH_SHORT).show();
                        Intent intentPage = new Intent(Constant.REFRESH_APPSTORE_ACTION);
                        intentPage.putExtra("fId", mFileFolderInfo.getParent());
                        sendBroadcast(intentPage);
                        finish();
                        break;
                    default:
                        break;
                }
            }
        };
        
    }
    
    private void initMusic()
    {
        Log.e("~~", "mFilePath：" + mFilePath);
        mFileFolderInfo.setMusicPath(mFilePath);
        initMusicView();
        initMusicListener();
        initMusicData();
        startMusicThread();
    }
    
    private void initMusicData()
    {
        // TODO Auto-generated method stub
        maxTime = mCloudDriveService.readyMusic(this, mFileFolderInfo);
        if (maxTime == -1)
        {
            Toast.makeText(this, "musicplayer error", 1).show();
            finish();
        }
        maxTime_tv.setText(formatData(maxTime));
        isPlaying = mCloudDriveService.isMusicPlaying();
        if (isPlaying)
        {
            btnPlayOrPause.setImageResource(R.mipmap.bt_widget_pause_nor);
        }
        else
        {
            btnPlayOrPause.setImageResource(R.mipmap.bt_widget_play_nor);
            if (maxTime != 0)
            {
                seekBar.setProgress(mCloudDriveService.getMusicProgress() * 100 / maxTime);
            }
            else
            {
                seekBar.setProgress(0);
            }
        }
    }
    
    @SuppressLint("SdCardPath")
    private void copyFileToTmep(String mdmPath)
    {
        // TODO Auto-generated method stub
        Log.i("liuxiang", mFileFolderInfo.getMusicPath() + "musicpath");
        
        iFileManager fm = FileManagerFactory.getFileManager(this);
        String tmpDataPath = "/data/data/" + getPackageName() + "/" + "tmpFile/";
        String tmpFileName = new File(mdmPath).getName();// get filename
        LogUtil.i(TAG, "copyFileToTmep:" + mdmPath + " | copy | tmpPath:" + tmpDataPath + tmpFileName);
        File file = new File(tmpDataPath + tmpFileName);
        musicPath = file.getAbsolutePath();
        mFileFolderInfo.setMusicPath(musicPath);
        if (file.exists() && 0 < file.length())
        {
            LogUtil.i(TAG, "tmpPath:" + tmpDataPath + tmpFileName + " __ is exist, no need to copy again...");
        }
        else
        {
            LogUtil.i(TAG, "tmpPath:" + tmpDataPath + tmpFileName + " __ is not exist, need to copy...");
            fm.decryptedFile(mdmPath, file.getAbsolutePath());
        }
    }
    
    private void initMusicView()
    {
        // TODO Auto-generated method stub
        btnPlayOrPause = (ImageView) findViewById(R.id.PlayOrPause_iv);
        seekBar = (SeekBar) findViewById(R.id.seekBar_music);
        currentTime_tv = (TextView) findViewById(R.id.music_currenttime);
        maxTime_tv = (TextView) findViewById(R.id.music_alltime);
        music_ll = (LinearLayout) findViewById(R.id.music_play_ll);
        mProgressbar.setVisibility(View.GONE);
        music_ll.setVisibility(View.VISIBLE);
        
    }
    
    private void startMusicThread()
    {
        // TODO Auto-generated method stub
        musicHandler = new Handler()
        {
            @Override
            public void handleMessage(Message msg)
            {
                currentTime = (Integer) msg.obj;
                if (currentTime == -1)
                {
                    isPlaying = false;
                    btnPlayOrPause.setImageResource(R.mipmap.bt_widget_play_nor);
                    seekBar.setProgress(0);
                    currentTime_tv.setText(formatData(0));
                }
                else
                {
                    seekBar.setProgress(currentTime * 100 / maxTime);
                    currentTime_tv.setText(formatData(currentTime));
                }
            }
        };
        isLoop = true;
        musicThread = new Thread()
        {
            @Override
            public void run()
            {
                while (isLoop)
                {
                    while (isLoop && isPlaying)
                    {
                        Message.obtain(musicHandler, 0, mCloudDriveService.getMusicProgress()).sendToTarget();
                        try
                        {
                            sleep(1000);
                        }
                        catch (InterruptedException e)
                        {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                    synchronized (musicThread)
                    {
                        try
                        {
                            this.wait();
                        }
                        catch (InterruptedException e)
                        {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                }
            }
        };
        musicThread.start();
    }
    
    private String formatData(int time)
    {
        return new SimpleDateFormat("mm:ss").format(time);
    }
    
    private void initMusicListener()
    {
        // TODO Auto-generated method stub
        seekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener()
        {
            
            @Override
            public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2)
            {
                // TODO Auto-generated method stub
                currentTime_tv.setText(formatData(maxTime * arg1 / 100));
            }
            
            @Override
            public void onStartTrackingTouch(SeekBar seekBar)
            {
                // TODO Auto-generated method stub
            }
            
            @Override
            public void onStopTrackingTouch(SeekBar seekBar)
            {
                // TODO Auto-generated method stub
                
                if (mCloudDriveService.isMusicPlaying())
                {
                    mCloudDriveService.setMusicProgress(maxTime * seekBar.getProgress() / 100);
                }
                else
                {
                    btnPlayOrPause.setImageResource(R.mipmap.bt_widget_pause_nor);
                    mCloudDriveService.playMusic();
                    isPlaying = true;
                    mCloudDriveService.setMusicProgress(maxTime * seekBar.getProgress() / 100);
                    synchronized (musicThread)
                    {
                        musicThread.notify();
                    }
                }
                
            }
        });
        btnPlayOrPause.setOnClickListener(playOrPauseListener);
    }
    
    OnClickListener playOrPauseListener = new OnClickListener()
    {
        
        @Override
        public void onClick(View v)
        {
            // TODO Auto-generated method stub
            if (mCloudDriveService.isMusicPlaying())
            {
                btnPlayOrPause.setImageResource(R.mipmap.bt_widget_play_nor);
                mCloudDriveService.pauseMusic();
                isPlaying = false;
            }
            else
            {
                btnPlayOrPause.setImageResource(R.mipmap.bt_widget_pause_nor);
                mCloudDriveService.playMusic();
                isPlaying = true;
                synchronized (musicThread)
                {
                    musicThread.notify();
                }
            }
            
        }
    };
    
    private void initCallBack()
    {
        mDownloadThumbnailCallback = new DownloadThumbnailCallback()
        {
            @Override
            public void onSuccess(String fileId)
            {
                notifyUpdateThumbnail(mThumbnailIconPath);
            }
        };
        
        mDownloadCallback = new DownloadCallback()
        {
            
            @Override
            public void onSuccess()
            {
                mHandler.sendEmptyMessage(FILE_DOWNLOAD_SUCCESS);
            }
            
            @Override
            public void onStart()
            {
                mHandler.sendEmptyMessage(FILE_START_DOENALOAD);
            }
            
            @Override
            public void onProgress(int currentProgress, long currentSize, long maxSize)
            {
                Message msg = Message.obtain(mHandler);
                msg.what = FILE_PROGRESS_DOWNLOAD;
                msg.obj = currentProgress;
                mHandler.sendMessage(msg);
            }
            
            @Override
            public void onFailure(Throwable t, int statusCode)
            {
                Message msg = mHandler.obtainMessage();
                if (statusCode == Constant.DOWNLOAD_CANCEL_SUCCESS_CODE)
                {
                    msg.arg1 = statusCode;
                }
                else if (statusCode == Constant.DOWNLOAD_FAIL_FILE_LARGERTHAN_CACHESIZE)
                {
                	msg.arg1 = Constant.DOWNLOAD_FAIL_FILE_LARGERTHAN_CACHESIZE;
                }
                else if (statusCode == Constant.DOWNLOAD_CANCEL_SUCCESS_CODE)
                {
                    return;
                }
                else if (statusCode == 901)
                {
                    msg.arg1 = 901;
                }
                else
                {
                    msg.arg1 = statusCode;
                }
                msg.what = FILE_DOWNLOAD_FAIL;
                mHandler.sendMessage(msg);
            }
        };
    }
    
    private void initCloudDriveService()
    {
        mServiceConnection = new ServiceConnection()
        {
            
            @Override
            public void onServiceConnected(ComponentName name, IBinder service)
            {
                
                mCloudDriveService = ((CloudDriveService.CenterShareDriveServiceServiceBinder) service).getService();
                
                if (!isDownloadMusic)
                {
                    downloadThumbnail();
                    downloadFile();
                }
                else
                {
                    initMusic();
                }
            }
            
            @Override
            public void onServiceDisconnected(ComponentName name)
            {
                // TODO Auto-generated method stub
                
            }
        };
        
        Intent intent = new Intent(this, CloudDriveService.class);
        intent.setAction("tokenAlarm");
        if (null != mServiceConnection)
        {
            bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE);
        }
        
    }
    
    private void initData()
    {
        if (mFileFolderInfo == null)
        {
            return;
        }
        
        mTvTitle.setText(mFileFolderInfo.getName());
        initMyIvLable();
        mTvName.setText(mFileFolderInfo.getName());
        mTvSize.setText(PublicTools.formatFileLength(mFileFolderInfo.getSize()));
    }
    
    private void initMyIvLable()
    {
        int typeImgResId = 0;
        if (PublicTools.isFileType(mFileFolderInfo.getName(), Constant.WORD_TYPE))
        {
            typeImgResId = R.mipmap.doc;
        }
        else if (PublicTools.isFileType(mFileFolderInfo.getName(), Constant.PPT_TYPE))
        {
            typeImgResId = R.mipmap.ppt;
        }
        else if (PublicTools.isFileType(mFileFolderInfo.getName(), Constant.IMAGE_TYPE))
        {
            typeImgResId = R.mipmap.empty_pic;
            mThumbnailIconPath = DirectoryUtil.genThumbnailFileFullName(this,
            		mFileFolderInfo.getOwnerBy(), mFileFolderInfo.getId(),mFileFolderInfo.getName());
            if (mThumbnailIconPath != null && new File(mThumbnailIconPath).exists())
            {
                notifyUpdateThumbnail(mThumbnailIconPath);
            }
        }
        else if (PublicTools.isFileType(mFileFolderInfo.getName(), Constant.RAR_TYPE))
        {
            typeImgResId = R.mipmap.rar;
        }
        else if (PublicTools.isFileType(mFileFolderInfo.getName(), Constant.ZIP_TYPE))
        {
            typeImgResId = R.mipmap.rar;
        }
        else if (PublicTools.isFileType(mFileFolderInfo.getName(), Constant.VIDEO_TYPE))
        {
            typeImgResId = R.mipmap.video;
        }
        else if (PublicTools.isFileType(mFileFolderInfo.getName(), Constant.MUSIC_TYPE))
        {
            typeImgResId = R.mipmap.music;
        }
        else if (PublicTools.isFileType(mFileFolderInfo.getName(), Constant.TXT_TYPE))
        {
            typeImgResId = R.mipmap.txt;
        }
        else if (PublicTools.isFileType(mFileFolderInfo.getName(), Constant.PDF_TYPE))
        {
            typeImgResId = R.mipmap.pdf;
        }
        else if (PublicTools.isFileType(mFileFolderInfo.getName(), Constant.EXCEL_TYPE))
        {
            typeImgResId = R.mipmap.excel;
        }
        else
        {
            typeImgResId = R.mipmap.default_file_icon;
        }
        
        mIvLabel.setImageResource(typeImgResId);
    }
    
    private void initView()
    {
        mContentView = LayoutInflater.from(this).inflate(R.layout.activity_file_download, null);
        setContentView(mContentView);
        mTvTitle = (TextView) findViewById(R.id.tv_file_browser_title);
        mIvLabel = (ImageView) findViewById(R.id.iv_label);
        mTvName = (TextView) findViewById(R.id.tv_name);
        mTvSize = (TextView) findViewById(R.id.tv_size);
        mProgressbar = (ProgressBar) findViewById(R.id.progressbar_file_download);
        
    }
    
    private void initDataFromIntentExtra()
    {
        Intent intent = getIntent();
        try
        {
            mFileFolderInfo = (FileFolderInfo) intent.getExtras().get(ClientConfig.FILE_FOLDER_INFO);
            Log.i("liuxiang", mFileFolderInfo + "down");
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
    
    private void notifyUpdateThumbnail(String iconPath)
    {
        Message msg_download = new Message();
        msg_download.what = HAS_PIC_THUMBNAIL;
        msg_download.obj = iconPath;
        mHandler.sendMessage(msg_download);
    }
    
    private void downloadFile()
    {
        final Context context = this;
        final iFileManager mdmTools = FileManagerFactory.getFileManager(context);
        final ICloudDriveService cloudDriveService = mCloudDriveService;
        long currentMills = System.currentTimeMillis();
        long time = PublicTools.getExpiredAt(this);
        if (time - currentMills <= 3 * 1000)
        {
            new Thread(new Runnable()
            {
                @Override
                public void run()
                {
                    try
                    {
                        Actions actions = new Actions(context);
                        if (null != cloudDriveService)
                        {
                            try
                            {
                                actions.smartUpdateAuthiorzation();
                            }
                            catch (Exception e)
                            {
                            }
                            
                        }
                        
                        if (!mdmTools.fileIsExist(lastPath))
                        {
                            mdmTools.createFilePath(lastPath);
                        }
                        
                        if (null != cloudDriveService)
                        {
                            openFile(cloudDriveService);
                            
                        }
                        // } catch (ClientException e1) {
                    }
                    catch (Exception e1)
                    {
                        // TODO Auto-generated
                        // catch
                        // block
                        LogUtil.e(TAG, "Download login exception");
                        e1.printStackTrace();
                        return;
                    }
                }
                
            }).start();
        }
        else
        {
            if (null == ShareDriveApplication.getInstance().getAuthorization())
            {
                // LogUtil.e(LOG_TAG,
                ShareDriveApplication.getInstance().setWnerID(PublicTools.getOwnerId(context));
                ShareDriveApplication.getInstance().setAuthorization(PublicTools.getAuthorization(context));
                SharedPreferences settings = context.getSharedPreferences(ClientConfig.settings,
                    Context.MODE_APPEND);
                CommonClient.getInstance().setServiceURL(settings.getString(ClientConfig.SERVER_ADDRESS, ""));
            }
            
            if (!mdmTools.fileIsExist(lastPath))
            {
                mdmTools.createFilePath(lastPath);
            }
            if (null != cloudDriveService)
            {
                openFile(cloudDriveService);
            }
        }
    }
    
    @Override
    protected void onDestroy()
    {
        super.onDestroy();
        if (isDownloadMusic)
        {
            isLoop = false;
            synchronized (musicThread)
            {
                musicThread.notify();
            }
        }
        unbindService(mServiceConnection);
    }
    
    private void downloadThumbnail()
    {
        if (PublicTools.isFileType(mFileFolderInfo.getName(), Constant.IMAGE_TYPE))
        {
            try
            {
                mThumbnailIconPath = DirectoryUtil.genThumbnailFileFullName(this,
                		mFileFolderInfo.getOwnerBy(), mFileFolderInfo.getId(),mFileFolderInfo.getName());
                
                File thumBnail2 = new File(mThumbnailIconPath);
                if (!thumBnail2.exists() && null != mCloudDriveService)
                {
                    if (!thumBnail2.getParentFile().exists())
                    {
                        thumBnail2.getParentFile().mkdirs();
                    }
                    mCloudDriveService.downloadThumbnailIcon(mFileFolderInfo.getOwnerBy(), mFileFolderInfo.getId(),
                        mThumbnailIconPath,
                        mDownloadThumbnailCallback);
                }
                else
                {
                    notifyUpdateThumbnail(mThumbnailIconPath);
                }
            }
            catch (Exception e)
            {
                // TODO: handle exception
                e.printStackTrace();
            }
        }
    }
    
    public static class DownloadThumbnailCallback implements IDownloadThumbnailCallback
    {
        
        @Override
        public void onStart()
        {
            
        }
        
        @Override
        public void onFailure(Throwable t)
        {
            
        }
        
        @Override
        public void onSuccess(String fileId)
        {
            
        }
        
        @Override
        public void onProgress(int currentProgress, long currentSize, long maxSize)
        {
            
        }
        
    }
    
    public static class DownloadCallback implements IDownloadCallback
    {
        
        @Override
        public void onStart()
        {
            
        }
        
        @Override
        public void onFailure(Throwable t, int statusCode)
        {
            
        }
        
        @Override
        public void onSuccess()
        {
            
        }
        
        @Override
        public void onProgress(int currentProgress, long currentSize, long maxSize)
        {
            
        }

		@Override
		public void onStop() {
			
		}

		@Override
		public void onCanceled() {
			
		}

		@Override
		public void onDettach() {
		}
        
    }
    
    public void onBackClick(View v)
    {
        if (!ShareDriveApplication.getInstance().isFastDoubleClick())
        {
            // onBackPressed();
            // removeTask
            if (!isDownloadMusic && !isFirstMusic)
            {
                removeTask();
            }
            
            this.finish();
            overridePendingTransition(R.anim.left_in, R.anim.right_out);
        }
    }
    
    @Override
    public void onBackPressed()
    {
        Log.i("xiangliu", "onbackpressed");
        // removeTask
        if (!isDownloadMusic && !isFirstMusic)
        {
            removeTask();
        }
        super.onBackPressed();
        overridePendingTransition(R.anim.left_in, R.anim.right_out);
    }
    
    private void removeTask()
    {
        if (mTask != null)
        {
            mTask.cancelDownloadTask();
        }
        
        if (mShareTask != null)
        {
            mShareTask.cancelDownloadTask(this);
        }
    }
    
    @Override
    public void finish()
    {
        // TODO Auto-generated method stub
        Log.i("xiangliu", "finished");
        super.finish();
        overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
    }
    
    private void openFile(final ICloudDriveService cloudDriveService)
    {
        if (mTask == null)
        {
            if (mFileFolderInfo.getIsInode() == -1)
            {
                mTask = mCloudDriveService.openFile(mFileFolderInfo.getOwnerBy(),
                    mFileFolderInfo.getParent(),
                    mFileFolderInfo.getId(),
                    ShareDriveApplication.getInstance().getAuthorization(),
                    mFileFolderInfo.getSize(),
                    mFilePath,
                    mDownloadCallback,
                    mFileFolderInfo);
                // mTask = cloudDriveService.getMyDownloadTask(
                // ShareDriveApplication.getInstance().getWnerID(),
                // mFileFolderInfo.getParent(), mFileFolderInfo.getId(),
                // ShareDriveApplication.getInstance().getAuthorization(),
                // 0, mFileFolderInfo.getSize(), mFilePath, mFileFolderInfo.getIsInode(),
                // mDownloadCallback);
            }
            else
            {
                String shareOwnerId = "";
                if (null != mFileFolderInfo.getSharedOwnerId())
                {
                    shareOwnerId = mFileFolderInfo.getSharedOwnerId();
                }
                else if (null != mFileFolderInfo.getOwnerBy())
                {
                    shareOwnerId = mFileFolderInfo.getOwnerBy();
                }
                String shareId = "";
                int isInode = 0;
                if (mFileFolderInfo.getiNodeId() != null)
                {
                    isInode = 0;
                    shareId = mFileFolderInfo.getiNodeId();
                }
                else
                {
                    isInode = 1;
                    shareId = mFileFolderInfo.getId();
                }
                
                // mTask = cloudDriveService.getMyDownloadTask(shareOwnerId,
                // mFileFolderInfo.getParent(), shareId,
                // ShareDriveApplication.getInstance().getAuthorization(),
                // 0, mFileFolderInfo.getSize(), mFilePath,mFileFolderInfo.getIsInode(),
                // mDownloadCallback);
                mShareTask = mCloudDriveService.openShareFile(shareOwnerId,
                    mFileFolderInfo.getParent(),
                    shareId,
                    0,
                    mFileFolderInfo.getSize(),
                    mFilePath,
                    mDownloadCallback,
                    mFileFolderInfo,
                    isInode);
            }
        }
        
    }
    
    @Override
    public void overridePendingTransition(int enterAnim, int exitAnim)
    {
        // TODO Auto-generated method stub
        super.overridePendingTransition(enterAnim, exitAnim);
    }
}
